package com.zx.security.config;

import com.zx.security.filter.TokenAuthFilter;
import com.zx.security.filter.TokenLoginFilter;
import com.zx.security.security.DefaultPasswordEncoder;
import com.zx.security.security.TokenLogoutHandler;
import com.zx.security.security.TokenManger;
import com.zx.security.security.UnauthEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Configuration
public class TokenWebConfig extends WebSecurityConfigurerAdapter {
    private TokenManger tokenManger;
    private RedisTemplate redisTemplate;
    private DefaultPasswordEncoder defaultPasswordEncoder;
    private UserDetailsService userDetailsService;
    @Autowired
    public TokenWebConfig(TokenManger tokenManger, RedisTemplate redisTemplate, DefaultPasswordEncoder defaultPasswordEncoder, UserDetailsService userDetailsService) {
        this.tokenManger = tokenManger;
        this.redisTemplate = redisTemplate;
        this.defaultPasswordEncoder = defaultPasswordEncoder;
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().authenticationEntryPoint(new UnauthEntryPoint())//没有权限访问执行
                                .and().csrf().disable()
                                .authorizeRequests()
                                .anyRequest().authenticated()
                                 .and().logout().logoutUrl("/admin/acl/index/logout")
                                 .addLogoutHandler(new TokenLogoutHandler(tokenManger,redisTemplate)).and()
                                 .addFilter(new TokenLoginFilter()).addFilter(new TokenAuthFilter(authenticationManager())).httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(defaultPasswordEncoder);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/api.*");
    }
}
